<template>
  <div id="strategy-list" class="strategy-list-container">
    <!-- 页面头部 -->
    <div class="header-section">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <i class="el-icon-document"></i> 攻略列表管理
          </h2>
          <p class="page-subtitle">管理平台所有攻略信息</p>
        </div>
        <div class="total-count">
          <div class="count-card">
            <span class="count-label">总攻略数</span>
            <span class="count-value">{{ total }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索筛选区 -->
    <div class="search-filter-card">
      <div class="filter-group">
        <div class="filter-item">
          <label class="filter-label">
            <i class="el-icon-document"></i> 攻略名称
          </label>
          <el-input
            v-model="searchName"
            placeholder="输入攻略名称搜索"
            clearable
            class="filter-input"
            @keyup.enter="handleSearch"
          />
        </div>
        <div class="filter-item">
          <label class="filter-label">
            <i class="el-icon-user"></i> 发表用户
          </label>
          <el-input
            v-model="searchUser"
            placeholder="输入用户名搜索"
            clearable
            class="filter-input"
            @keyup.enter="handleSearch"
          />
        </div>
      </div>
      
      <div class="action-buttons">
        <el-button 
          type="primary"  
          @click="handleSearch"
          class="search-btn"
        >
          查询
        </el-button>
        <el-button  
          @click="resetSearch"
          class="reset-btn"
        >
          重置
        </el-button>
        <el-button 
          type="danger" 
          @click="handleBatchDelete"
          :disabled="multipleSelection.length === 0"
          class="batch-delete-btn"
        >
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-table-card">
      <el-table
        :data="pagedStrategies"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        empty-text="暂无攻略数据"
        :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
        @selection-change="handleSelectionChange"
        ref="strategyTable"
      >
        <el-table-column 
          type="selection"
          width="55"
          align="center"
        />
        <el-table-column 
          prop="strategyName" 
          label="攻略名称" 
          min-width="220"
        >
          <template #default="{ row }">
            <div class="strategy-name-cell">
              <i class="el-icon-document"></i>
              <span class="strategy-name">{{ row.strategyName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column 
          prop="userName" 
          label="发表用户" 
          width="150" 
          align="center"
        >
          <template #default="{ row }">
            <span class="username">{{ row.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column 
          prop="modificationTime" 
          label="发表时间" 
          width="180" 
          align="center"
          sortable
        >
          <template #default="{ row }">
            <div class="time-cell">
              <span>{{ formatDate(row.modificationTime) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column 
          label="操作" 
          width="200" 
          align="center"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="primary"
              @click="handleDetail(row)"
              plain
            >
              详情
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              plain
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页控制 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        background
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑攻略信息" width="400px">
      <el-form :model="editStrategy" label-width="100px">
        <el-form-item label="攻略名称">
          <el-input v-model="editStrategy.strategyName" />
        </el-form-item>
        <el-form-item label="地区ID">
          <el-input v-model="editStrategy.regionId" />
        </el-form-item>
        <el-form-item label="发表人ID">
          <el-input v-model="editStrategy.userId" />
        </el-form-item>
        <el-form-item label="景点ID">
          <el-input v-model="editStrategy.scenicSpotId" />
        </el-form-item>
        <el-form-item label="跟团游ID">
          <el-input v-model="editStrategy.groupTourId" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="editStrategy.strategyContent" type="textarea" />
        </el-form-item>
        <el-form-item label="发表时间">
          <el-input v-model="editStrategy.modificationTime" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { fetchStrategyList, searchStrategyByName, fetchStrategyListByUser, deleteStrategy, updateStrategy } from '../../../api/strategy'

const router = useRouter()
const searchName = ref('')
const searchUser = ref('')
const strategies = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const editDialogVisible = ref(false)
const editStrategy = ref({})
const multipleSelection = ref([])
const strategyTable = ref(null)

const pagedStrategies = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return strategies.value.slice(start, end)
})

function loadStrategies() {
  fetchStrategyList()
    .then(res => {
      strategies.value = (res.data || []).map(item => ({
        strategyId: item.strategyId,
        strategyName: item.strategyName,
        regionId: item.regionId,
        userId: item.userId,
        scenicSpotId: item.scenicSpotId,
        groupTourId: item.groupTourId,
        strategyContent: item.strategyContent,
        modificationTime: item.modificationTime,
        userName: item.userName,
      }))
      total.value = strategies.value.length
    })
    .catch(error => {
      console.error('fetchStrategyList error', error)
      ElMessage.error('获取攻略列表失败')
    })
}

function handleSearch() {
  if (!searchName.value && !searchUser.value) {
    loadStrategies()
  } else if (searchUser.value && !searchName.value) {
    fetchStrategyListByUser(searchUser.value).then(res => {
      strategies.value = (res.data || []).map(item => ({
        strategyId: item.strategyId,
        strategyName: item.strategyName,
        regionId: item.regionId,
        userId: item.userId,
        scenicSpotId: item.scenicSpotId,
        groupTourId: item.groupTourId,
        strategyContent: item.strategyContent,
        modificationTime: item.modificationTime,
        userName: item.userName,
      }))
      total.value = strategies.value.length
    })
  } else {
    searchStrategyByName(searchName.value, searchUser.value).then(res => {
      strategies.value = (res.data || []).map(item => ({
        strategyId: item.strategyId,
        strategyName: item.strategyName,
        regionId: item.regionId,
        userId: item.userId,
        scenicSpotId: item.scenicSpotId,
        groupTourId: item.groupTourId,
        strategyContent: item.strategyContent,
        modificationTime: item.modificationTime,
        userName: item.userName,
      }))
      total.value = strategies.value.length
    })
  }
}

function resetSearch() {
  searchName.value = ''
  searchUser.value = ''
  handleSearch()
}

onMounted(() => {
  loadStrategies()
})

async function handleDetail(row) {
  router.push({ name: 'StrategyDetail', params: { id: row.strategyId } })
}

function handleDelete(row) {
  ElMessageBox.confirm(`确定要删除攻略 ${row.strategyName} 吗？`, '提示', {
    type: 'warning',
  }).then(() => {
    deleteStrategy(row.strategyId).then(res => {
      handleSearch();
      ElMessage.success('删除成功')
    }).catch(() => {
      ElMessage.error('删除失败')
    })
  })
}

function handleSizeChange(size) {
  pageSize.value = size
}

function handlePageChange(page) {
  currentPage.value = page
}

function handleEdit(row) {
  editStrategy.value = { ...row }
  editDialogVisible.value = true
}

async function handleEditSave() {
  try {
    await updateStrategy(editStrategy.value)
    editDialogVisible.value = false
    ElMessage.success('修改成功')
    handleSearch() // 刷新列表
  } catch (e) {
    ElMessage.error('修改失败')
  }
}

function formatDate(value) {
  if (!value) return ''
  const d = new Date(value)
  if (isNaN(d.getTime())) return 'Invalid Date'
  return d.getFullYear() + '-' + 
         String(d.getMonth()+1).padStart(2, '0') + '-' + 
         String(d.getDate()).padStart(2, '0') + ' ' + 
         String(d.getHours()).padStart(2, '0') + ':' + 
         String(d.getMinutes()).padStart(2, '0') + ':' + 
         String(d.getSeconds()).padStart(2, '0')
}

function handleSelectionChange(val) {
  multipleSelection.value = val
}

async function handleBatchDelete() {
  if (multipleSelection.value.length === 0) return
  ElMessageBox.confirm(
    `确定要批量删除这 ${multipleSelection.value.length} 条攻略吗？`,
    '批量删除',
    { type: 'warning' }
  ).then(async () => {
    for (const strategy of multipleSelection.value) {
      await deleteStrategy(strategy.strategyId)
    }
    strategies.value = strategies.value.filter(
      s => !multipleSelection.value.some(sel => sel.strategyId === s.strategyId)
    )
    total.value = strategies.value.length
    multipleSelection.value = []
    if (strategyTable.value) strategyTable.value.clearSelection()
    ElMessage.success('批量删除成功')
  })
}
</script>

<style scoped lang="scss">
/* 整体容器 */
.strategy-list-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  background-color: #f8fafc;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

/* 头部区域 */
.header-section {
  background: linear-gradient(135deg, #a0c4e4 0%, #7fa8d1 100%);
  padding: 20px 25px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(160, 196, 228, 0.2);
  margin-bottom: 24px;
  color: #2c3e50;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  .page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 10px;
    
    i {
      font-size: 28px;
      color: #2c3e50;
    }
  }
  
  .page-subtitle {
    margin: 5px 0 0;
    font-size: 14px;
    color: #4a5568;
  }
}

.total-count {
  .count-card {
    background: rgba(255, 255, 255, 0.7);
    padding: 12px 20px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border: 1px solid #e2e8f0;
    
    .count-label {
      font-size: 14px;
      margin-bottom: 5px;
      color: #4a5568;
    }
    
    .count-value {
      font-size: 24px;
      font-weight: 700;
      color: #2c3e50;
    }
  }
}

/* 搜索筛选卡片 */
.search-filter-card {
  background-color: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.filter-group {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  
  .filter-label {
    font-size: 14px;
    color: #606266;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 6px;
    font-weight: 500;
    
    i {
      font-size: 16px;
    }
  }
  
  .filter-input {
    :deep(.el-input__inner) {
      border-radius: 8px;
      height: 40px;
      line-height: 40px;
    }
  }
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  
  .search-btn {
    background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    height: 40px;
    
    &:hover {
      opacity: 0.9;
    }
  }
  
  .reset-btn {
    border-radius: 8px;
    padding: 10px 20px;
    height: 40px;
    border: 1px solid #dcdfe6;
    
    &:hover {
      color: #4299e1;
      border-color: #c6e2ff;
      background-color: #ecf5ff;
    }
  }
  
  .batch-delete-btn {
    border-radius: 8px;
    padding: 10px 20px;
    height: 40px;
    
    &:hover {
      opacity: 0.9;
    }
    
    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
  }
}

/* 数据表格卡片 */
.data-table-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin-bottom: 20px;
  
  :deep(.el-table) {
    border-radius: 12px 12px 0 0;
    overflow: hidden;
    
    th {
      background-color: #f8fafc !important;
      font-weight: 600;
      color: #4a5568;
    }
    
    td {
      padding: 12px 0;
    }
    
    .el-table__row:hover {
      background-color: #f0f4f8;
    }
  }
}

.username {
  font-weight: 500;
  color: #2c3e50;
}

.strategy-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  
  i {
    font-size: 18px;
    color: #4299e1;
  }
  
  .strategy-name {
    font-size: 15px;
    font-weight: 500;
    color: #3182ce;
  }
}

.time-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  color: #718096;
  
  i {
    font-size: 16px;
  }
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 15px 0;
  
  :deep(.el-pagination) {
    .btn-prev, .btn-next {
      border-radius: 8px;
      border: 1px solid #e2e8f0;
    }
    
    .el-pager li {
      border-radius: 8px;
      border: 1px solid #e2e8f0;
      margin: 0 4px;
      background: white;
      
      &.active {
        background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
        color: white;
      }
    }
    
    .el-pagination__jump {
      .el-input__inner {
        border-radius: 8px;
      }
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .filter-group {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    justify-content: center;
  }
}
</style>

<style>
/* 全局样式覆盖 */
.delete-message-box {
  border-radius: 12px !important;
  
  .el-message-box__header {
    padding: 20px 20px 10px;
  }
  
  .el-message-box__content {
    padding: 15px 20px;
  }
  
  .el-message-box__btns {
    padding: 10px 20px 20px;
  }
}

.success-message {
  border-radius: 8px !important;
  background: #f0f9eb !important;
  border: none !important;
}

.error-message {
  border-radius: 8px !important;
  background: #fef0f0 !important;
  border: none !important;
}
</style>